import * as Blockly from 'blockly/core'

/**
 * Construct the blocks required by the flyout for the category.
 * @param {!Blockly.Workspace} workspace The workspace containing procedures.
 * @return {!Array.<!Element>} Array of XML block elements.
 */
Blockly.builtInParam = {}
Blockly.builtInParam.flyoutCategory = function (workspace) {
  var xmlList = []
  // if (Blockly.Blocks['params_input']) {
  //   var block = Blockly.utils.xml.createElement('block')
  //   block.setAttribute('type', 'params_input')
  //   xmlList.push(block)
  // }

  function populateParams(paramList) {
    for (var i = 0; i < paramList.length; i++) {
      var name = paramList[i]
      var block = Blockly.utils.xml.createElement('block')
      block.setAttribute('type', 'params_input')
      var field = Blockly.utils.xml.createElement('field')
      field.setAttribute('name', 'CODE')
      field.appendChild(Blockly.utils.xml.createTextNode(name))
      block.setAttribute('gap', 16)
      block.appendChild(field)
      xmlList.push(block)
    }
  }

  var list = Blockly.builtInParam.allParams(workspace)
  if (!list.length) {
    var button = document.createElement('button');
    button.setAttribute('text', '请先选中积木');
    button.setAttribute('disabled', 'true');
    xmlList.push(button);
  }
  populateParams(list)
  return xmlList
}


Blockly.builtInParam.allParams = function (root) {
  const allBlocks = root.getAllBlocks() || []
  const current = allBlocks.find(item => item.isClicked === true)
  if (!current) return []
  // const blocks = root.getBlocksByType('params_input', false) || []
  const blocks = getParent(current)
  const list = blocks.filter(item => item.type === 'params_input').map(function (block) {
    return (block).getFieldValue('CODE')
  })
  return [...new Set(list)]
}

function getParent(block) {
  let node = [];
  let currentNode = block;
  node.push(currentNode);
  const children = currentNode.getChildren() || []
  node = [...children, node]
  if (currentNode.parentBlock_) {
    const children = currentNode.parentBlock_.getChildren() || []
    if (children) {
      node = [currentNode.parentBlock_, ...children, ...node]
    }
    node = [...getParent(currentNode.parentBlock_), ...node];
  }
  return node
}
